let fs = require('fs');
let pdf = require('html-pdf');
let optDefault = { format: 'Letter' };
const puppeteer = require('puppeteer');

// options.output 输出文件位置，必填
exports.createFile = function(htmlPath, options) {
  let html = fs.readFileSync(htmlPath, 'utf8');
  let opt = Object.assign(optDefault, options)
  if (!opt.output) {
    console.log('没有指定pdf输出文件路径！')
    return
  }
  pdf.create(html, opt).toFile(opt.output, function(err, res) {
    if (err) return console.log(err);
    console.log(res);
  });
}

exports.createStream = function(htmlPath, options) {
  let html = fs.readFileSync(htmlPath, 'utf8');
  let opt = Object.assign(optDefault, options)
  let p = new Promise(function(resolve, reject) {
    pdf.create(html, opt).toFile(opt.output, function(err, stream){
      console.log('create file success')
      resolve()
      // return stream
    });
  })
  return p
  // pdf.create(html).toStream(function(err, stream){
  //   stream.pipe(fs.createWriteStream('./foo.pdf'));
  // });
}

exports.createPdfByPage = async function(url, fileName) {
  let footer = `<style>#footer { font-size: 12px;  width: 100%; }</style>
  <div style="width: 80%;margin: 0 auto;">
    <span class='title'></span>
    <span style="float: right;"><span>第</span><span class='pageNumber'></span><span>页 / </span><span class='totalPages'></span></span>
  </div>
  `
  // <script>
  //   var pageNum = document.getElementById("num");
  //   pageNum.remove()
  //   var template = document.getElementById("template")
  //   template.style.background = 'red';
  // </script>

  const browser = await puppeteer.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox']});
  const page = await browser.newPage();
  await page.goto(url, {waitUntil: 'networkidle2'});

  let buffer = await page.pdf({
    path: 'temp/' + fileName,
    format: 'A4',
    printBackground: true,
    margin: {
      top: '15mm',
      bottom: '15mm'
    },
    displayHeaderFooter: true,
    footerTemplate: footer,
    headerTemplate: '<div></div>',
  });
  
  await browser.close();
  return buffer;
}